module CommentsHelper
  
  # Show comment poster
  def show_commenter(id)
    user ||= User.find(id) rescue nil
    user.nil? ? "System message" : user
  end
  
  # Initialize comment
  def initialize_comment_body(comment, type)
    initialize_comment(type) do
      commenter = show_commenter(comment.commenter_id)
      unless commenter == "System message"
        "<div id='comment_#{comment.id}'> #{image_tag commenter.photo.url(:small)} <em>#{link_to commenter.name, user_path(comment.commenter_id)} on #{comment.created_at.to_s(:long)}</em>#{simple_format comment.body}</div>"
      else
        "<div id='comment_#{comment.id}'><em>#{commenter} on #{comment.created_at.to_s(:long)}</em>#{simple_format comment.body}</div>"
      end
    end
  end
  
  # Show comment
  def show_comment(comment)
    unless comment.commenter_id.nil?
      if comment.private?
        if current_user.id == comment.user_id || current_user.id == comment.commenter_id
          initialize_comment_body(comment, :private)
        end
      else
        initialize_comment_body(comment, :normal)
      end
    else
      if current_user.id == comment.user_id
        initialize_comment_body(comment, :system)
      end
    end
  end
  
  protected
  
  # Detect comment type
  def initialize_comment(type)
    case type.to_sym
      when :normal then
        content_tag(:div, :class => 'user-comment comment') { yield }
      when :private then
        content_tag(:div, :class => 'private-comment comment') { yield }
      when :system then
        content_tag(:div, :class => 'system-comment comment') { yield }
    end
  end
  
end
